package com.mlz.mlzmall.ui.adapter;

import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.CartInfo;
import com.mlz.mlzmall.ui.activity.frag.main.ShoppingCartFragment;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.DialogView;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class ShoppingCartAdapter extends BaseAdapter{
    private ShoppingCartFragment context;
    private int resource;
    String sessionKey;
    int totalCout;
    ViewHolder vh;
    String tag = "ShoppingCart";
    public ArrayList<CartInfo.CartProductDto> data = new ArrayList<>();
    public boolean dataAll;
    private ImageLoader imageLoader = ImageLoader.getInstance();    // 新建静态实例对象
    public static final String action = "changCount.broadcast.action";    // 发广播用的action


    public ShoppingCartAdapter(ShoppingCartFragment context, int resource, ArrayList<CartInfo.CartProductDto> data, boolean dataAll) {
        this.context = context;
        this.resource = resource;
        this.data = data;
        this.dataAll = dataAll;
        sessionKey = ACache.get(context.getActivity()).getAsString("sessionKeyLogin");
        context.setNetResponses(context);
        vh = new ViewHolder();
    }

    @Override
    public int getCount() {
        if (data == null) {
            return 0;
        } else {
            return data.size();
        }
    }

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    View view;
    int aaa = 0;
    DecimalFormat df = new DecimalFormat("0.00");//使价格后不保留小数

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {

        final int item = position;

        convertView = LayoutInflater.from(context.getActivity()).inflate(resource, null);
        vh.pro_shopPrice = (TextView) convertView.findViewById(R.id.pro_shopPrice);
        vh.pro_image = (ImageView) convertView.findViewById(R.id.pro_image);
        vh.pro_name = (TextView) convertView.findViewById(R.id.pro_name);
        vh.pro_add = (Button) convertView.findViewById(R.id.pro_add); // 增加按钮
        vh.pro_reduce = (Button) convertView.findViewById(R.id.pro_reduce); // 减少按钮
        vh.cb_order_selete = (CheckBox) convertView.findViewById(R.id.cb_order_selete);  // 单件商品的勾选按钮
        vh.pro_count = (TextView) convertView.findViewById(R.id.pro_count);    // 选择的商品数量
        vh.taxRate = (TextView) convertView.findViewById(R.id.tax_rate); // 税率
        vh.imageViewDelete = (TextView) convertView.findViewById(R.id.iVDeleteProduct); // 删除商品
        view = convertView;
        view.setTag(vh);

        if (StringTools.allselect == 11) {
            vh.cb_order_selete.setChecked(StringTools.allSelectNSC);
            if (aaa < data.size() - 1) {
                aaa++;
            } else {
                aaa = 0;
                StringTools.allselect = 22;
            }


        } else if (StringTools.allselect == 12) {
            vh.cb_order_selete.setChecked(StringTools.allSelectSELF);
            if (aaa < data.size() - 1) {
                aaa++;
            } else {
                aaa = 0;
                StringTools.allselect = 22;
            }

        } else {
            vh.cb_order_selete.setChecked(data.get(item).isSelected());
        }
        //显示图片
        imageLoader.displayImage(data.get(item).getImage(), vh.pro_image);
        // 商品名
        vh.pro_name.setText(data.get(item).getName().toString());
        // 商品税率
        vh.taxRate.setText(String.valueOf("税率:" + df.format(data.get(item).getTariffRates() * 100) + "%"));
        // 商品单价
        vh.pro_shopPrice.setText(df.format(data.get(item).getPrice()));
        // 该件商品的数量
        vh.pro_count.setText(String.valueOf(data.get(item).getQuantity()));

        //减少数量
        vh.pro_reduce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout ParentL = (RelativeLayout) v.getParent();
                TextView countReduce = (TextView) ParentL.findViewById(R.id.pro_count);
                int amount = 1;
                if (null != countReduce && !"".equals(countReduce.getText())) {
                    amount = Integer.valueOf(String.valueOf(countReduce.getText()));
                    if (amount > 1) {
                        amount--;
                        totalCout--;
                        data.get(item).setQuantity(amount);
                    } else return;
                }
                editTheProductCount(amount, data.get(item).getProductId());
                countReduce.setText(String.valueOf(amount));
                notifyDataSetChanged();
            }

        });

        // 增加方法
        vh.pro_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RelativeLayout ParentL = (RelativeLayout) v.getParent();
                TextView countAdd = (TextView) ParentL.findViewById(R.id.pro_count);
                int amount = 1;
                if (null != countAdd && !"".equals(countAdd.getText())) {
                    amount = Integer.valueOf(String.valueOf(countAdd.getText()));
                    amount++;
                    totalCout++;
                    data.get(item).setQuantity(amount);
                }
                editTheProductCount(amount, data.get(item).getProductId());
                countAdd.setText(String.valueOf(amount));
                notifyDataSetChanged();
            }
        });
        // 商品的选择与取消
        vh.cb_order_selete.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) { //单独选中为2
                    selected(2, data.get(item));
                    data.get(item).setSelected(true);
                } else { // 单独取消为1
                    selected(1, data.get(item));
                    data.get(item).setSelected(false);
                }
                notifyDataSetChanged();
            }
        });

//       删除商品
        vh.imageViewDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                //删除商品 333 表示删除商品
                final DialogView dialogView = new DialogView(context.getActivity(),
                        R.layout.dialogview_tow, R.style.pager_dialog,2,"是否确定删除商品?");
                dialogView.setOnBtnClickListener(new DialogView.OnBtnClickListener() {
                    @Override
                    public void onclick(int i) {
                        if (i == 0) {//当点击确定的时候清除掉多余杂质
                            //删除商品 333 表示删除商品
                            selected(333, data.get(item));
                            data.remove(item);

//                            if(data.size() == 0){
//                                context.sendBroadcast(new Intent("dataIsEmpty"));
//                            }
                        } else if (i == 1) {
                            dialogView.cancel();//点击取消的时候消除提示框
                        }
                    }
                });
                dialogView.show();
            }
        });
        return convertView;
    }


    class ViewHolder {
        ImageView pro_image;
        TextView pro_name;
        TextView pro_shopPrice;
        Button pro_add;
        Button pro_reduce;
        CheckBox cb_order_selete;  // 商品的选择
        TextView imageViewDelete;      // 删除商品
        TextView taxRate, trunkName;
        TextView pro_count;
    }


    // 修改当前商品的数量
    public void editTheProductCount(final int countEdit, final int productId) {
        Map map = new HashMap();
        map.put("productId", productId);
        map.put("quantity", countEdit);
        context.request(Request.Method.POST, URL.CART.EDIT_QTY, map,sessionKey, tag, 100);

    }

    // 取消、选中处理
    public void selected(final int seleType, final CartInfo.CartProductDto seletedProduct) {

        Map map = new HashMap();
        switch (seleType) {
            // 单独未选中
            case 1:
                map.clear();
                map.put("productId", seletedProduct.getProductId());
                map.put("warehouse", seletedProduct.getWarehouse());
                context.request(Request.Method.POST, URL.CART.UNSELECT, map,sessionKey, tag, 100);
                break;
            // 单独选中
            case 2:
                map.clear();
                map.put("productId", seletedProduct.getProductId());
                map.put("warehouse", seletedProduct.getWarehouse());
                context.request(Request.Method.POST, URL.CART.SELECT, map,sessionKey, tag, 100);
                break;

            // 删除商品
            case 333:
                map.clear();
                map.put("productId", seletedProduct.getProductId());
                map.put("warehouse", seletedProduct.getWarehouse());
                context.request(Request.Method.POST, URL.CART.REMOVE, map,sessionKey, tag, 104);
                break;
        }


    }

}

